package com.app.samba;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.app.samba.bean.LocalMediaBean;
import com.app.samba.bean.MessageEvent;
import com.app.samba.thread.DownRunnable;
import com.app.samba.thread.DownTaskRunnable;
import com.app.samba.util.MediaFileUtil;
import com.app.samba.util.NetConstant;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static com.app.samba.DebugLog.SAMBA_DOWN_UP;


/**
 * Created Date 2019/7/1
 *
 * @author liangkun
 * description：
 */
public class DownActivity extends AppCompatActivity {

    private Button button;
    private Button btnUp;
    private Button btnDown;
    private Button btnQuery;
    private List<LocalMediaBean> localFiles;
    private ExecutorService service;
    private DownTaskRunnable runnable;
    private ThreadPoolExecutor executor;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_down);
        button = findViewById(R.id.btn_get);
        btnUp = findViewById(R.id.btn_up);
        btnDown = findViewById(R.id.btn_down);
        btnQuery = findViewById(R.id.btn_query);
        EventBus.getDefault().register(this);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaFileUtil.getInstance().getLocalImags(DownActivity.this);
            }
        });

        btnUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                service = Executors.newFixedThreadPool(3);

                for (int i = 0; i < localFiles.size(); i++) {
                    service.submit(new DownRunnable(localFiles.get(i).getFilePath(), 1));
                }
//                runnable = new DownTaskRunnable(localFiles, 1);
//                service.submit(runnable);
//                service.execute(new DownTaskRunnable(2));
//                service.execute(new DownTaskRunnable(3));

//                executor = new ThreadPoolExecutor(
//                        3,
//                        3,
//                        60,
//                        TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.AbortPolicy());
//                service.submit(runnable);
//                for (int i = 0; i < 10; i++) {
//                    final int finalI = i;
//                    executor.execute(new Runnable() {
//                        @Override
//                        public void run() {
//                            try {
//                                DebugLog.d(SAMBA_DOWN_UP + "第" + finalI);
//                                Thread.sleep(1000);
//                            } catch (InterruptedException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    });
//                }

            }
        });
        btnQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //在主线程调用shutdown
//                service.shutdownNow();
//                DebugLog.d(SAMBA_DOWN_UP + "线程池已经关闭--- ");

//                if(!service.isShutdown()){
//                    DebugLog.d(SAMBA_DOWN_UP+"线程运行中-----开始停止");
////                    service.shutdown();
//                    service.shutdownNow();
//                }else {
//                    DebugLog.d(SAMBA_DOWN_UP+"线程停止了-----开始运行");
//                    service.submit(runnable);
//                }

//                service.shutdown();
                shutdownAndAwaitTermination(service);


//                List<Runnable> runnables = service.shutdownNow();
//                DebugLog.d(SAMBA_DOWN_UP+"runnables.size()--- "+runnables.size());
//                try {
//                while (!service.awaitTermination(1, TimeUnit.MILLISECONDS)) {
//                    DebugLog.d(SAMBA_DOWN_UP+"线程池没有关闭--- ");
//                }
//                } catch (InterruptedException ie) {
//                    // (Re-)Cancel if current thread also interrupted
//                    DebugLog.d(SAMBA_DOWN_UP+"线程运行中-----开始停止3333333--- ");
//
//                }
//                DebugLog.d(SAMBA_DOWN_UP+"线程池已经关闭--- ");


            }
        });
    }

    private void shutdownAndAwaitTermination(ExecutorService pool) {
        try {
            // 向学生传达“问题解答完毕后请举手示意！”
            pool.shutdown();

            // 向学生传达“XX分之内解答不完的问题全部带回去作为课后作业！”后老师等待学生答题
            // (所有的任务都结束的时候，返回TRUE)
            if (!pool.awaitTermination(5, TimeUnit.SECONDS)) {
                // 超时的时候向线程池中所有的线程发出中断(interrupted)。
                DebugLog.d(SAMBA_DOWN_UP + "线程池关闭 ");
                pool.shutdownNow();
            }
        } catch (InterruptedException e) {
            // awaitTermination方法被中断的时候也中止线程池中全部的线程的执行。
            DebugLog.d(SAMBA_DOWN_UP + "awaitTermination interrupted--- ");
            pool.shutdownNow();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MsgEvent(MessageEvent msgEvent) {
        String fileCode = msgEvent.getFileCode();
        localFiles = getLocalFiles(msgEvent);
        switch (fileCode) {
            case NetConstant.FILE_IMAGE_CODE:
                DebugLog.d(SAMBA_DOWN_UP + " 图片---- " + localFiles.size());
                break;
            case NetConstant.FILE_VIDEO_CODE:
                DebugLog.d(SAMBA_DOWN_UP + " 视频---- " + localFiles.size());
                break;
            case NetConstant.FILE_MUSIC_CODE:
                DebugLog.d(SAMBA_DOWN_UP + " 音乐---- " + localFiles.size());
                break;
        }


    }


    /**
     * 获取本地文件数据
     *
     * @param msgEvent 传递
     * @return
     */
    private List<LocalMediaBean> getLocalFiles(MessageEvent msgEvent) {
        List<LocalMediaBean> mediaBeanList = new ArrayList<>();
        HashMap<String, List<LocalMediaBean>> mapFile = msgEvent.getMapFile();
        Iterator iterator = mapFile.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = (String) entry.getKey();
//            DebugLog.d(LOGPHONE + " dirPath ---------------------------------------------------" + key);
            List<LocalMediaBean> list = (List<LocalMediaBean>) entry.getValue();
            mediaBeanList.addAll(list);
        }
        return mediaBeanList;
    }

}
